package com.example.micro.netty.server.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * 群聊Server
 */
public class GroupChatServer {

    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    //初始化工作
    public GroupChatServer() {

        try {

            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            //将listenChannel  注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //监听
    public void listen() {

        try {
            //循环处理
            while (true) {
                int readyChannels = selector.select(5000);
                if (readyChannels > 0) {
                    //遍历得到selectionKey集合
                    Set<SelectionKey> keySet = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = keySet.iterator();

                    while (iterator.hasNext()) {
                        //取出selectionKey
                        SelectionKey selectionKey = iterator.next();

                        //监听到accept
                        if (selectionKey.isAcceptable()) {
                            SocketChannel socketChannel = listenChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + " 上线 ");
                        }

                        //通道发现读事件
                        if (selectionKey.isReadable()) {
                            readData(selectionKey);
                        }

                        //当前key删除，防止重复处理
                        iterator.remove();
                    }

                }
                System.out.println("等待....");
            }
        } catch (Exception e) {

        }

    }

    //读取客户端消息
    private void readData(SelectionKey key) {

        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            int count = socketChannel.read(buffer);

            if (count > 0) {
                String msg = new String(buffer.array());
                System.out.println("from 客户端：" + msg);

                //向其他的客户端转发消息（除去自己），专门写一个方法来处理
                this.sendInfoToOtherClients(msg, socketChannel);
            }
        } catch (IOException e1) {
            //发生异常，说明当前准备群发的客户端离线了
            try {
                System.out.println(socketChannel.getRemoteAddress() + " 离线了..。 ");
                //取消注册
                key.cancel();
                //关闭通道
                socketChannel.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }

    }

    //转发消息给其他的客户端
    private void sendInfoToOtherClients(String msg, SocketChannel selfSocketChannel) throws IOException {
        System.out.println("服务器转发消息中......");
        for (SelectionKey selectionKey : selector.keys()) {
            Channel targetChannel = selectionKey.channel();
            if (!(targetChannel instanceof SocketChannel)
                    || targetChannel == selfSocketChannel) {
                continue;
            }
            SocketChannel targetSocketChannel = (SocketChannel) targetChannel;
            ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
            targetSocketChannel.write(buffer);
        }
    }

    public static void main(String[] args) {
        //创建服务端服务
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();

    }

}
